import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';

class CharacteristicTile extends StatefulWidget {
  final BluetoothCharacteristic characteristic;
  final List<DescriptorTile> descriptorTiles;
  final BluetoothDevice device;

  const CharacteristicTile({super.key, required this.characteristic, required this.descriptorTiles, required this.device});

  @override
  State<CharacteristicTile> createState() => _CharacteristicTileState();
}

class _CharacteristicTileState extends State<CharacteristicTile> {

  List<int> _value = [];
  late StreamSubscription<List<int>> _lastValueSubscription;

  @override
  void initState() {
    super.initState();
    _lastValueSubscription =
        widget.characteristic.lastValueStream.listen((value) {
          _value = value;
          if (mounted) {
            setState(() {});
          }
        });
  }

  @override
  void dispose() {
    _lastValueSubscription.cancel();
    super.dispose();
  }

  BluetoothCharacteristic get c => widget.characteristic;

  List<int> _getRandomBytes() {
    // 将字符串转换为字节数组
    String data = 'Hello, Bluetooth!';
    List<int> bytes = utf8.encode(data);
    return bytes;
  }

  Future onReadPressed() async {
    try {
      await c.read();
      debugPrint("Read: Success");
    } catch (e) {
      debugPrint("Read Error:");
    }
  }

  // 写入数据
  Future<void> write(List<List<int>> allSubValue, int index) async {
    await onWritePressed(allSubValue[index]).then((result){
      index++;
      if (index > allSubValue[index].length) {
        debugPrint('数据全部发送完毕');
      } else {
        write(allSubValue, index);
      }
    }).catchError((err){
      debugPrint('第$index个数据包错误!!!__________$err');
    }) ;
  }

  // 分包处理
  Future<void> splitWrite(List<int> value) async {
    int chunk = widget.device.mtuNow - 3;
    List<List<int>> allSubValue = [];
    for (int i = 0; i < value.length; i += chunk) {
      List<int> subValue = value.sublist(i, min(i + chunk, value.length));
      allSubValue.add(subValue);
    }
    write(allSubValue, 0);
  }

  Future onWritePressed(value) async {
    try {

      // String data = '''
      //   ! 0 400 560 620 1
      //   PW 400
      //   TEXT 3,8 0 10 100 物料编码：CES001
      //   GAP-SENSE
      //   FORM
      //   PRINT
      // ''';
      // List<int> bytes = [
      //   0x33, 0x32, 0x48, 0x32, 0x34, 0x30, 0x30, 0x32,
      //   0x53, 0x54, 0x30, 0x32, 0x54, 0x32, 0x30, 0x31,
      //   0x53, 0x30, 0x30, 0x31, 0x0D, 0x0A, 0x45, 0x4E,
      //   0x44, 0x51, 0x52, 0x0D, 0x0A, 0x47, 0x41, 0x50,
      //   0x2D, 0x53, 0x45, 0x4E, 0x53, 0x45, 0x0D, 0x0A,
      //   0x46, 0x4F, 0x52, 0x4D, 0x0D, 0x0A, 0x50, 0x52,
      //   0x49, 0x4E, 0x54, 0x0D, 0x0A
      // ];

      await c.write(value, withoutResponse: c.properties.writeWithoutResponse);
      debugPrint("c--------------Write: Success");
      if (c.properties.read) {
        await c.read();
      }
    } catch (e) {
      debugPrint("c--------------Write Error:");
    }

  }

  Future onSubscribePressed() async {
    try {
      String op = c.isNotifying == false ? "Subscribe" : "Unubscribe";
      await c.setNotifyValue(c.isNotifying == false);
      debugPrint("$op : Success");
      if (c.properties.read) {
        await c.read();
      }
      if (mounted) {
        setState(() {});
      }
    } catch (e) {
      debugPrint("Subscribe Error:");
    }
  }

  Widget buildUuid(BuildContext context) {
    String uuid = '0x${widget.characteristic.uuid.str.toUpperCase()}';
    return Text(uuid);
  }

  Widget buildValue(BuildContext context) {
    String data = _value.toString();
    return Text(
      data,
      style: const TextStyle(fontSize: 13),
    );
  }

  Widget buildReadButton(BuildContext context) {
    return TextButton(
        child: const Text(
          "Read",
          style: TextStyle(fontSize: 13),
        ),
        onPressed: () async {
          await onReadPressed();
          if (mounted) {
            setState(() {});
          }
        });
  }

  Widget buildWriteButton(BuildContext context) {
    bool withoutResp = widget.characteristic.properties.writeWithoutResponse;
    return TextButton(
        child: Text(withoutResp ? "WriteNoResp" : "Write",
            style: const TextStyle(fontSize: 13, color: Colors.grey)),
        onPressed: () async {
          // await onWritePressed();
          if (mounted) {
            setState(() {});
          }
        });
  }

  Widget buildSubscribeButton(BuildContext context) {
    bool isNotifying = widget.characteristic.isNotifying;
    return TextButton(
        child: Text(isNotifying ? "取消" : "使用"),
        onPressed: () async {
          await onSubscribePressed();
          if (mounted) {
            setState(() {});
          }
        });
  }

  Widget buildButtonRow(BuildContext context) {
    bool read = widget.characteristic.properties.read;
    bool write = widget.characteristic.properties.write;
    bool notify = widget.characteristic.properties.notify;
    bool indicate = widget.characteristic.properties.indicate;
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (read) buildReadButton(context),
        if (write) buildWriteButton(context),
        if (notify || indicate) buildSubscribeButton(context),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return ExpansionTile(
      title: ListTile(
        title: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            const Text(
              'Characteristic',
              style: TextStyle(fontSize: 13),
            ),
            buildUuid(context),
            buildValue(context),
          ],
        ),
        subtitle: buildButtonRow(context),
        contentPadding: const EdgeInsets.all(0.0),
      ),
      children: widget.descriptorTiles,
    );
  }
}

class DescriptorTile extends StatefulWidget {
  final BluetoothDescriptor descriptor;

  const DescriptorTile({super.key, required this.descriptor});

  @override
  State<DescriptorTile> createState() => _DescriptorTileState();
}

class _DescriptorTileState extends State<DescriptorTile> {
  List<int> _value = [];

  late StreamSubscription<List<int>> _lastValueSubscription;

  @override
  void initState() {
    super.initState();
    _lastValueSubscription = widget.descriptor.lastValueStream.listen((value) {
      _value = value;
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  void dispose() {
    _lastValueSubscription.cancel();
    super.dispose();
  }

  BluetoothDescriptor get d => widget.descriptor;

  List<int> _getRandomBytes() {
    // 将字符串转换为字节数组
    String data = 'Hello, Bluetooth!';
    return utf8.encode(data);
  }

  Future onReadPressed() async {
    try {
      await d.read();
      debugPrint("Descriptor Read : Success");
    } catch (e) {
      debugPrint("Descriptor Read Error:");
    }
  }

  Future onWritePressed() async {
    try {
      debugPrint('_getRandomBytes----------${_getRandomBytes()}');

      List<int> dataToSend = [
        0x33, 0x32, 0x48, 0x32, 0x34, 0x30, 0x30, 0x32,
        0x53, 0x54, 0x30, 0x32, 0x54, 0x32, 0x30, 0x31,
        0x0D, 0x0A, 0x50, 0x57, 0x20, 0x34, 0x30, 0x30,
        0x0D, 0x0A, 0x54, 0x45, 0x58, 0x54, 0x20, 0x33,
        0x2C, 0x38, 0x20, 0x30, 0x20, 0x31, 0x30, 0x20,
        0x31, 0x30, 0x30, 0x20, 0xC2, 0xA2, 0xC2, 0xB2,
        0xC2, 0xA4, 0xC2, 0xA1, 0xC2, 0xA0, 0x43, 0x45,
        0x53, 0x30, 0x30, 0x31, 0x0D, 0x0A, 0x45, 0x4E,
        0x44, 0x51, 0x52, 0x0D, 0x0A, 0x47, 0x41, 0x50,
        0x2D, 0x53, 0x45, 0x4E, 0x53, 0x45, 0x0D, 0x0A,
        0x46, 0x4F, 0x52, 0x4D, 0x0D, 0x0A, 0x50, 0x52,
        0x49, 0x4E, 0x54, 0x0D, 0x0A
      ];
      await d.write(dataToSend);
      debugPrint("d------------Descriptor Write : Success");
    } catch (e) {
      debugPrint("d------------Descriptor Write Error:");
    }
  }

  Widget buildUuid(BuildContext context) {
    String uuid = '0x${widget.descriptor.uuid.str.toUpperCase()}';
    return Text(
      uuid,
      style: const TextStyle(fontSize: 13),
    );
  }

  Widget buildValue(BuildContext context) {
    String data = _value.toString();
    return Text(
      data,
      style: const TextStyle(fontSize: 13),
    );
  }

  Widget buildReadButton(BuildContext context) {
    return TextButton(
      onPressed: onReadPressed,
      child: const Text("Read"),
    );
  }

  Widget buildWriteButton(BuildContext context) {
    return TextButton(
      onPressed: onWritePressed,
      child: const Text("Write"),
    );
  }

  Widget buildButtonRow(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        buildReadButton(context),
        buildWriteButton(context),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          const Text(
            'Descriptor',
            style: TextStyle(fontSize: 13),
          ),
          buildUuid(context),
          buildValue(context),
        ],
      ),
      subtitle: buildButtonRow(context),
    );
  }
}

